<script setup>
import {ref, reactive, onMounted} from 'vue'
import {Plus, Search} from '@element-plus/icons-vue'
import {ElMessage, ElLoading} from 'element-plus'
import {useRoute} from "vue-router";
import server from "../utils/request.js";
import {getUserIdFromToken} from "../utils/jwtUtil.js"
import {importImage} from "../utils/load_assets.js";

// 根据登录的token信息拿到登录的id
const userId = getUserIdFromToken();
// 表单数据
const formData = ref({
  id: '',
  username: '',
  name: '',
  image: '',
  phone: '',
  intro: '',
  address: '', // 新增地址字段
  longitude: '', // 经度
  latitude: ''  // 纬度
})

// 表单验证规则
const formRules = reactive({
  name: [
    {required: true, message: '请输入商户名', trigger: 'blur'},
    {min: 2, max: 50, message: '商户名长度在 2 到 50 个字符', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur'}
  ],
  intro: [
    {max: 500, message: '商家描述不能超过500个字符', trigger: 'blur'}
  ],
  address: [
    {required: true, message: '请输入地址', trigger: 'blur'}
  ]
})

// 上传相关配置
const uploadUrl = 'http://localhost:8080/merchant/upload'
const merchantForm = ref(null)

// 保存商家信息
const saveMerchant = async () => {
  if (!merchantForm.value) {
    ElMessage.error('表单实例未找到');
    return;
  }
  try {
    await merchantForm.value.validate();
    const {data} = await server.put(`/merchant/`, formData.value);
    if (data.code === 200) {
      ElMessage.success('保存成功');
    } else {
      ElMessage.error(`保存失败：${data.msg}`);
    }
  } catch (error) {
    console.log('表单验证失败', error);
  }
};

// 图片上传成功处理
const handleImageUpload = (response) => {
  formData.value.image = response.data
  ElMessage.success('图片上传成功')
}

// 图片上传前验证
const beforeImageUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJpgOrPng) {
    ElMessage.error('只能上传JPG/PNG格式的图片')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB')
    return false
  }
  return true
}

// 通过后端代理获取经纬度（核心修改：不直接调用高德API，而是调用自己的后端接口）
const getLocationByAddress = async () => {
  if (!formData.value.address.trim()) {
    ElMessage.warning('请输入地址信息')
    return
  }

  const loading = ElLoading.service({
    lock: true,
    text: '正在获取位置信息...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    // 调用后端代理接口，传递地址参数
    const {data} = await server.get('/merchant/geocode', {
      params: {address: formData.value.address}
    })

    if (data.code === 200 && data.data) {
      formData.value.longitude = data.data.longitude
      formData.value.latitude = data.data.latitude
      ElMessage.success('位置信息获取成功')
    } else {
      ElMessage.error(`获取位置失败: ${data.msg || '地址解析失败'}`)
      formData.value.longitude = ''
      formData.value.latitude = ''
    }
  } catch (error) {
    ElMessage.error('获取位置信息失败，请稍后重试')
    console.error('地理编码错误:', error)
  } finally {
    loading.close()
  }
}
// 获取商家详情数据
const fetchMerchantDetail = async () => {
  try {
    let {data} = await server.get(`merchant/${userId}`)
    Object.assign(formData.value, data.data)
  } catch (error) {
    ElMessage.error('获取商家详情失败')
  }
}
// 页面加载时获取数据
onMounted(() => {
  fetchMerchantDetail()
})
</script>

<template>
  <el-card class="page-card">
    <div slot="header" class="card-header">
      <span>编辑商家</span>
      <div class="button-group">
        <el-button size="small">取消</el-button>
        <el-button type="primary" size="small" @click="saveMerchant">保存</el-button>
      </div>
    </div>

    <el-form
        ref="merchantForm"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="merchant-form"
    >
      <el-form-item label="商家ID" prop="id">
        <el-input v-model="formData.id" disabled></el-input>
      </el-form-item>

      <el-form-item label="商家账号" prop="username">
        <el-input v-model="formData.username" disabled></el-input>
      </el-form-item>

      <el-form-item label="商户名" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>

      <el-form-item label="商家照片" prop="image">
        <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleImageUpload"
            :before-upload="beforeImageUpload"
        >
          <el-image
              v-if="importImage.reportImg(formData.image)"
              :src="importImage.reportImg(formData.image)"
              style="width: 200px; height: 150px; object-fit: contain"
          ></el-image>
          <div v-else class="upload-placeholder">
            <el-icon>
              <Plus/>
            </el-icon>
            <div class="upload-text">点击上传</div>
          </div>
        </el-upload>
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>

      <el-form-item label="商家描述" prop="intro">
        <el-input
            v-model="formData.intro"
            type="textarea"
            placeholder="请输入商家描述"
        ></el-input>
      </el-form-item>

      <el-form-item label="商家地址" prop="address">
        <el-row :gutter="10">
          <el-col :span="20">
            <el-input
                v-model="formData.address"
                placeholder="请输入详细地址（如：北京市朝阳区建国路88号）"
            ></el-input>
          </el-col>
          <el-col :span="4">
            <el-button
                type="primary"
                @click="getLocationByAddress"
                style="width: 100%"
            >
              <el-icon>
                <Search/>
              </el-icon>
              <span>解析</span>
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="经度" prop="longitude">
        <el-input v-model="formData.longitude" placeholder="地址解析后自动填充" readonly></el-input>
      </el-form-item>

      <el-form-item label="纬度" prop="latitude">
        <el-input v-model="formData.latitude" placeholder="地址解析后自动填充" readonly></el-input>
      </el-form-item>

    </el-form>
  </el-card>
</template>

<style scoped>
.merchant-page {
  padding: 20px;
}

.page-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.edit-btn {
  margin-left: auto;
}

.button-group {
  display: flex;
  gap: 10px;
}

.merchant-form {
  margin-top: 20px;
}

.avatar-uploader {
  display: inline-block;
}

.upload-placeholder {
  width: 200px;
  height: 150px;
  border: 1px dashed #ccc;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.upload-text {
  margin-top: 8px;
  color: #666;
  font-size: 14px;
}
</style>